package com.scnu.edu.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scnu.edu.config.AliPayConfig;
import com.scnu.edu.config.OrderModel;
import com.scnu.edu.entity.Order;
import com.scnu.edu.entity.User;
import com.scnu.edu.service.OrderService;
import com.scnu.edu.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/api/alipay")
public class AliPayController {
    @Autowired
    private AliPayConfig aliPayConfig;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;

    private OrderModel orderModel = null;
    private String token = "";

    @PostMapping("/pay")
    public String alipay(
            @RequestHeader(required = false) String token,
            @RequestBody OrderModel orderModel
    ) throws AlipayApiException {
        // 1. 生成订单号（保持原有逻辑）
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        String orderNum = time + user;
        orderModel.setOrderNo(orderNum);

        // 2. 保存订单（保持原有逻辑）
        Order order = new Order();
        order.setUserId(orderModel.getUserId());
        order.setOrderNo(orderNum);
        order.setProductName(orderModel.getProductName());
        order.setAmount(orderModel.getAmount());
        order.setStatus(0); // 待支付
        order.setCreateTime(new Date());
        order.setVipDays(orderModel.getVipDays());
        orderService.save(order);

        // 3. 调用支付宝接口生成支付表单
        String form = aliPayConfig.sendRequestToAlipay(
                orderNum,
                orderModel.getAmount().doubleValue(),
                orderModel.getProductName()
        );

        // 4. 直接返回表单字符串（Spring 会自动设置 Content-Type 为 text/html）
        return form;
    }

    @GetMapping("/toSuccess")
    public String returnToSuccessPage(String out_trade_no, Model model, HttpSession session) {
        try {
            String query = aliPayConfig.query(out_trade_no);
            JSONObject jsonObject = JSONObject.parseObject(query);
            Map<String, Object> response = (Map<String, Object>) jsonObject.get("alipay_trade_query_response");

            if ("TRADE_SUCCESS".equals(response.get("trade_status"))) {
                Order order = orderService.lambdaQuery()
                        .eq(Order::getOrderNo, out_trade_no)
                        .one();
                if (order != null) {
                    order.setStatus(1);
                    order.setPayTime(new Date());
                    orderService.updateById(order);

                    // 直接调用 UserService 更新VIP状态
                    User user = userService.updateVipStatus(order.getUserId(), order.getVipDays());
                    if (user != null) {
                        session.setAttribute("user", user);
                    }
                }
                model.addAttribute("message", "支付成功");
            } else {
                model.addAttribute("message", "支付失败");
            }
            return "order/result";
        } catch (Exception e) {
            model.addAttribute("message", "支付处理异常");
            return "order/result";
        }
    }

}